package com.z6school.manage.service.impl;

import com.z6school.manage.common.annotation.RequiredLog;
import com.z6school.manage.common.exception.ServiceException;
import com.z6school.manage.common.pojo.Nodes;
import com.z6school.manage.common.pojo.UserMenuVo;
import com.z6school.manage.mapper.MenusMapper;
import com.z6school.manage.mapper.RolesMenusMapper;
import com.z6school.manage.mapper.UserRolesMapper;
import com.z6school.manage.po.Menus;
import com.z6school.manage.service.MenuService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenusMapper menusMapper;
    @Autowired
    private RolesMenusMapper rolesMenusMapper;
    @Autowired
    private UserRolesMapper userRolesMapper;
    @Override
    @RequiresPermissions("sys:menu:view")
    public  List<Map<String, Object>>  doFindObject() {
        return menusMapper.doFindObject();
    }

    @Override
    @RequiredLog(operation = "删除菜单信息")
    @RequiresPermissions("sys:menu:delete")
    public int doDeleteObject(Integer id) {
        if(id==null || id<1)throw new IllegalArgumentException("id值无效");
        int childCount = menusMapper.getChildCount(id);
        System.out.println(123);
        if(childCount>0)throw new ServiceException("请先删除子菜单");
        rolesMenusMapper.doDeleteObject("menuId",id);
        int rows = menusMapper.doDeleteObject(id);
        if(rows==0)throw new ServiceException("记录可能已经不存在");
        return rows;
    }

    @Override
    @RequiredLog(operation = "查询菜单树节点")
    public List<Nodes> findZtreeMenuNodes() {
        return menusMapper.findZtreeMenuNodes();
    }

    @Override
    @RequiredLog(operation = "保存菜单信息")
    @RequiresPermissions("sys:menu:save")
    public int saveObject(Menus entity) {
        int rows = menusMapper.insertObject(entity);
        return rows;
    }

    @Override
    @RequiredLog(operation = "更新菜单信息")
    @RequiresPermissions("sys:menu:update")
    public int updateObject(Menus entity) {
        int rows = menusMapper.updateObject(entity);
        if(rows==0)throw new ServiceException("记录可能已经不存在");
        return rows;
    }

    @Override
    public List<UserMenuVo> findUserMenusByUserId(Integer id) {
        //1.对用户id进行判断
        if(id==null)
            throw new IllegalArgumentException("该用户不存在");
        //2.基于用户id查找用户对应的角色id
        List<Integer> roleIds = userRolesMapper.findRoleIdsByUserId(id);
        //3.基于角色id获取角色对应的菜单信息,并进行封装
        List<Integer> menuIds = rolesMenusMapper.findMenuIdsByRoleIds(roleIds);
        //4.基于菜单id获取用户对应的菜单信息并返回
        return menusMapper.findMenusByIds(menuIds);
    }
}
